<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="100px" size="small">
      <el-form-item label="" prop="decDeviceId">
        <el-input
          v-model="queryParams.decDeviceId"
          clearable
          placeholder="请输入设备编号"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          clearable
          placeholder="请输入设备名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="" prop="stationId">
        <el-select v-model="queryParams.stationId" clearable placeholder="请选择场站">
          <el-option
            v-for="dict in stationList"
            :key="dict.id"
            :label="dict.stationName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="agentId">
        <el-select v-model="queryParams.agentId" clearable placeholder="请选择代理商">
          <el-option
            v-for="dict in agentList"
            :key="dict.id"
            :label="dict.agentName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="dictValue">
        <el-select v-model="queryParams.dictValue" clearable placeholder="请选择设备类型">
          <el-option
            v-for="dict in dictList"
            :key="dict"
            :label="dict"
            :value="dict"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择设备状态">
          <el-option
            v-for="dict in statusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['business:manager:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['business:manager:edit']"
              >设置</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['business:manager:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['business:manager:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managerList" :stripe="true" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column align="center" label="设备编号" prop="decDeviceId" width="180"/>
      <el-table-column align="center" label="设备名称" prop="deviceName" show-overflow-tooltip width="200"/>
      <el-table-column align="center" label="场站" prop="stationName" show-overflow-tooltip width="200"/>
      <el-table-column align="center" label="归属" prop="agentName" width="150"/>
      <el-table-column align="center" label="设备类型" prop="protocolName"/>
      <el-table-column align="center" label="端口数量" prop="chargePortNumber" width="80"/>
      <el-table-column align="center" label="允许平台化" prop="enablePlatform" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enablePlatform"
            :active-value=1
            :inactive-value=0
            disabled
            style="display: block"
            @click.native.prevent="updateManager(scope.row,'enablePlatform','enablePrivate')">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="允许私有化" prop="enablePrivate" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enablePrivate"
            :active-value=1
            :inactive-value=0
            disabled
            style="display: block"
            @click.native.prevent="updateManager(scope.row,'enablePrivate','enablePlatform')">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册时间" prop="registerTime" width="200">
        <template slot-scope="scope">
          <span>{{ formatDate(Number(scope.row.registerTime)) }}</span>
        </template>

      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status==1?'success':scope.row.status==0?'danger':'info'">{{ statusList[scope.row.status].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="设置" width="160">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['business:manager:setting']"
            icon="el-icon-setting"
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleSetting' }]"
            type="text"
            @click="handleSetting(scope.row),active=scope.$index+'handleSetting'"
          >属性设置
          </el-button>
          <el-button
            v-hasPermi="['business:manager:setting']"
            icon="el-icon-setting"
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleMode' }]"
            type="text"
            @click="handleMode(scope.row),active=scope.$index+'handleMode'"
          >计费模型
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="150">
        <template slot-scope="scope">
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:manager:edit']"
          >修改</el-button>-->

          <el-button
            v-hasPermi="['business:manager:query']"
            icon="el-icon-s-order"
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleDetail' }]"
            type="text"
            @click="handleDetail(scope.row),active=scope.$index+'handleDetail'"
          >详情
          </el-button>
          <el-button
            v-if="scope.row.status==1"
            v-hasPermi="['business:manager:remove']"
            icon="el-icon-refresh-right"
            size="mini"
            type="text"
            @click="handleManagerRestart(scope.row)"
          >重启
          </el-button>
          <!--          <el-switch
                      :value="value"
                      @change="handleChange(scope.$index, scope.row)"
                      active-text="开启"
                      inactive-text="关闭">
                    </el-switch>-->

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改充电桩管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="刷卡板版本" prop="cardBoardVersion">
          <el-input v-model="form.cardBoardVersion" placeholder="请输入刷卡板版本"/>
        </el-form-item>
        <el-form-item label="物联卡号" prop="cardNo">
          <el-input v-model="form.cardNo" placeholder="请输入物联卡号"/>
        </el-form-item>
        <el-form-item label="充电枪口数量" prop="chargePortNumber">
          <el-input v-model="form.chargePortNumber" placeholder="请输入充电枪口数量"/>
        </el-form-item>
        <el-form-item label="充电枪实时数据上报频率" prop="chargePortReportFre">
          <el-input v-model="form.chargePortReportFre" placeholder="请输入充电枪实时数据上报频率"/>
        </el-form-item>
        <el-form-item label="通讯模块版本" prop="communicationModuleValue">
          <el-input v-model="form.communicationModuleValue" placeholder="请输入通讯模块版本"/>
        </el-form-item>
        <el-form-item label="DTU信号值" prop="dtuSignalValue">
          <el-input v-model="form.dtuSignalValue" placeholder="请输入DTU信号值"/>
        </el-form-item>
        <el-form-item label="心跳上报频率" prop="heartbeatReportFre">
          <el-input v-model="form.heartbeatReportFre" placeholder="请输入心跳上报频率"/>
        </el-form-item>
        <el-form-item label="十六进制物联卡号" prop="hexCardNo">
          <el-input v-model="form.hexCardNo" placeholder="请输入十六进制物联卡号"/>
        </el-form-item>
        <el-form-item label=" 十六进制集成电路卡识别码" prop="hexIccId">
          <el-input v-model="form.hexIccId" placeholder="请输入 十六进制集成电路卡识别码"/>
        </el-form-item>
        <el-form-item label="十六进制设备识别码" prop="hexImei">
          <el-input v-model="form.hexImei" placeholder="请输入十六进制设备识别码"/>
        </el-form-item>
        <el-form-item label="集成电路卡识别码" prop="iccId">
          <el-input v-model="form.iccId" placeholder="请输入集成电路卡识别码"/>
        </el-form-item>
        <el-form-item label="设备识别码" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入设备识别码"/>
        </el-form-item>
        <el-form-item label="最后心跳时间" prop="lastHeartbeatTime">
          <el-input v-model="form.lastHeartbeatTime" placeholder="请输入最后心跳时间"/>
        </el-form-item>
        <el-form-item label="自检触发漏保动作时间" prop="leakageProtectionActionTime">
          <el-input v-model="form.leakageProtectionActionTime" placeholder="请输入自检触发漏保动作时间"/>
        </el-form-item>
        <el-form-item label="主控版本" prop="masterControlVersion">
          <el-input v-model="form.masterControlVersion" placeholder="请输入主控版本"/>
        </el-form-item>
        <el-form-item label="最大充电电流" prop="maxChargeCurrents">
          <el-input v-model="form.maxChargeCurrents" placeholder="请输入最大充电电流"/>
        </el-form-item>
        <el-form-item label="最大充电功率" prop="maxChargePower">
          <el-input v-model="form.maxChargePower" placeholder="请输入最大充电功率"/>
        </el-form-item>
        <el-form-item label="最大充电电压" prop="maxChargeVoltage">
          <el-input v-model="form.maxChargeVoltage" placeholder="请输入最大充电电压"/>
        </el-form-item>
        <el-form-item label="漏保最大电流" prop="maxCurrentsOfLeakageProtection">
          <el-input v-model="form.maxCurrentsOfLeakageProtection" placeholder="请输入漏保最大电流"/>
        </el-form-item>
        <!--<el-form-item label="首次注册时间" prop="registerTime">
          <el-input v-model="form.registerTime" placeholder="请输入首次注册时间" />
        </el-form-item>-->
        <el-form-item label="自检结果" prop="selfInspectionResults">
          <el-input v-model="form.selfInspectionResults" placeholder="请输入自检结果"/>
        </el-form-item>
        <el-form-item label="信号值" prop="signalVal">
          <el-input v-model="form.signalVal" placeholder="请输入信号值"/>
        </el-form-item>
        <el-form-item label="充电场站" prop="stationId">
          <el-input v-model="form.stationId" placeholder="请输入充电场站"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  详情 -->
    <el-dialog :title="title" :visible.sync="openDetail" append-to-body width="90%">
      <el-dialog
        :visible.sync="innerVisible"
        append-to-body
        title=""
        width="35%">
        <div style="display: flex;justify-content: center">
          <qr-item :chargePort="chargePort" :decDeviceId="decDeviceId" :deviceName="deviceName" :logo="imageUrl"
                   :showLogo="showLogo" :stationName="stationName" :text="innerVisibleText"
                   :value="codeUrl"></qr-item>
        </div>
      </el-dialog>
      <div class="items">
        <div class="itemleft1">
          <el-tabs v-model="activeName" type="border-card" @tab-click="handleClickTabs">
            <el-tab-pane label="基础属性" name="基础属性">
              <el-descriptions :column="1" border class="margin-top" title="">
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-mobile-phone"></i>
                    设备ID
                  </template>
                  {{ deviceVoMap.deviceId }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    设备名称
                  </template>
                  {{ deviceVoMap.deviceName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-location-outline"></i>
                    所属场站
                  </template>
                  {{ deviceVoMap.stationName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-tickets"></i>
                    运行状态
                  </template>
                  {{ deviceVoMap.status == 1 ? '在线' : '离线' }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-office-building"></i>
                    注册时间
                  </template>
                  {{ parseTime(deviceVoMap.registerTime) }}
                </el-descriptions-item>

              </el-descriptions>
            </el-tab-pane>
            <el-tab-pane label="设备硬件" name="second">
              <el-tabs type="border-card">
                <el-tab-pane v-for="(item, index) in deviceSetUpInfoMap" :key="index" :label="item.label">
                  <el-form ref="infoForm" label-width="170px">
                    <el-form-item v-for="(itemSub, key) in item.list" :key="key" :label="itemSub.setUpShowName">
                      {{ itemSub.settingValue }}
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <el-tab-pane label="计费模型" name="third">

              <el-table v-if="billingModelStageType == 'T'" :data="webBillingModelShowVoMap.billingModelStageList"
                        height="300">
                <el-table-column align="center" label="序号" prop="sortNum"/>
                <el-table-column align="center" label="起始时间" prop="beginDuration">
                  <template slot-scope="scope">
                    {{ ChangeHourMinutestr(scope.row.beginDuration) }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="服务费"
                  prop="serviceFeeShow">
                </el-table-column>
                <el-table-column
                  align="center"
                  label="电价"
                  prop="electricityPriceShow">
                  <template slot-scope="scope">
                    {{ scope.row.electricityPriceShow }}
                  </template>
                </el-table-column>
              </el-table>
              <el-table v-if="billingModelStageType == 'P'" :data="webBillingModelShowVoMap.billingModelStageList"
                        height="300">
                <el-table-column align="center" label="序号" prop="sortNum"/>
                <el-table-column align="center" label="阶段最大功率（单位：W）" prop="beginDuration">
                  <template slot-scope="scope">
                    {{ scope.row.beginDuration }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="服务费"
                  prop="serviceFeeShow">
                </el-table-column>
                <el-table-column
                  align="center"
                  label="电价"
                  prop="electricityPrice">
                  <template slot-scope="scope">
                    {{ scope.row.electricityPriceShow }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="运行参数" name="fourth">
              <el-tabs type="border-card">
                <el-tab-pane v-for="(item, index) in runTimeMap" :key="index" :label="item.label">
                  <el-form ref="infoForm" label-width="170px">
                    <el-form-item v-for="(itemSub, key) in item.list" :key="key" :label="itemSub.setUpShowName">
                      {{ itemSub.settingValue }}
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <el-tab-pane label="故障记录" name="five">
              <el-table v-loading="loading" :data="deviceFaultRecordList">
                <el-table-column align="center" label="故障编号" prop="id" width="130"/>
                <!--<el-table-column label="故障详细数据" align="center" prop="hexFaultInfo" />-->
                <el-table-column align="center" label="枪口号" prop="chargePort" width="60"/>
                <!--<el-table-column label="设备ID" align="center" prop="deviceId" />-->
                <el-table-column align="center" label="故障码" prop="faultCode" width="60"/>
                <el-table-column align="center" label="故障描述" prop="faultMsg" show-overflow-tooltip/>
                <el-table-column align="center" label="故障状态" prop="faultStatus">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.faultStatus == 0 ? 'primary' : 'danger'" effect="dark">
                      {{ scope.row.faultStatus == 0 ? '故障解除' : '故障产生' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="故障生成时间" prop="removalTime" width="150">
                  <template slot-scope="scope">
                    <span>{{ formatDate(Number(scope.row.createTime)) }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="故障解除时间" prop="removalTime" width="150">
                  <template slot-scope="scope">
                    <span>{{ formatDate(Number(scope.row.removalTime)) }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="解除方式" prop="removalType">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.removalType == 0 ? 'danger' : 'success'" effect="dark">
                      {{ scope.row.removalType == 0 ? '设备报告' : '手动解除' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                  <template slot-scope="scope">
                    <el-button
                      v-hasPermi="['business:deviceFaultRecord:remove']"
                      icon="el-icon-delete"
                      size="mini"
                      type="text"
                      @click="handleDeleteRecodes(scope.row, scope.$index)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total2>0"
                :limit.sync="queryParams2.pageSize"
                :page.sync="queryParams2.pageNum"
                :total="total2"
                layout="total, prev, pager, next"
                @pagination="getList2"
              />
            </el-tab-pane>
            <el-tab-pane label="故障分析" name="six">
              <div v-loading="binShow">
                <bin-chart v-if="binData.length > 0" ref="binChart" :pieData="binData"/>
                <el-empty v-else description="暂无数据"></el-empty>
              </div>
            </el-tab-pane>
            <el-tab-pane label="设备热力图" name="seven">
              <heat-map v-if="chargeOrderCountMapList.length > 0" ref="heatMap"
                        :chargeOrderCountMapList="chargeOrderCountMapList" :faultCountMapList="faultCountMapList" :heartCountMapList="heartCountMapList"/>
              <el-empty v-else description="暂无数据"></el-empty>
            </el-tab-pane>
          </el-tabs>


        </div>
        <div id="container" class="itemleft2"></div>
      </div>
      <!--<el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
        <line-chart :chart-data="lineChartData" />
      </el-row>-->

      <div slot="footer" class="dialog-footer footer_all">
        <el-row style="margin-top: -80px;">
          <div style="margin: 20px 10px 10px 0; font-weight: bold; text-align: left">枪口状态</div>
          <el-button v-for="(item, index) in chargePortVoList" :key="index"
                     :type="item.status == 0 ? 'success' : 'danger'" @click="openInnerVisible(index, item.port)">&nbsp;{{
              item.port
            }}&nbsp;
          </el-button>
        </el-row>
        <div>
          <el-button type="primary" @click="openDetail=false">确 定</el-button>
          <el-button @click="openDetail=false">取 消</el-button>
        </div>
      </div>

    </el-dialog>
    <!-- 属性设置弹框 -->
    <el-dialog :title="title" :visible.sync="openSetting" append-to-body width="600px">
      <el-tabs type="border-card" @tab-click="tabSetting">
        <el-tab-pane v-for="(item, index) in infoForm" :key="index" :label="item.label">
          <el-form ref="infoForm" :model="formInfo" label-width="170px">
            <!--<el-form-item :label="itemSub.setUpShowName" prop="cardBoardVersion" v-for="(itemSub, key) in infoForm[index]" :key="key">
              <el-input v-model="form.cardBoardVersion" placeholder="请输入刷卡板版本" />
            </el-form-item>-->
            <dynamic-form-item
              v-for="(itemSub, key) in item.list"
              :key="itemSub.id"
              :item="itemSub"
              :value="itemSub.settingValue"
              @input="handleInput($event, index, key)"
            ></dynamic-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSetting">确 定</el-button>
        <el-button @click="cancelSetting">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 计费模型弹框 -->
    <el-dialog :title="title" :visible.sync="openMode" append-to-body width="80%">
      <el-descriptions :column="3" border class="margin-top" title="">
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            设备ID
          </template>
          {{ modeDetail.deviceId }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            设备名称
          </template>
          {{ modeDetail.deviceName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-office-building"></i>
            设备类型
          </template>
          {{ modeDetail.dictLabel }}
        </el-descriptions-item>
      </el-descriptions>
      <el-form :inline="true" label-position="left" label-width="100px" size="small" style="margin: 20px 0">
        <el-form-item label="计费模型" prop="dictValue">
          <el-select v-model="selectManager" placeholder="请选择计费模型" @change="changeModes">
            <el-option
              v-for="(item,index) in modelList"
              :key="index"
              :label="item.billingModelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        v-if="billingModel.billingModelStageType == 'P'"
        v-loading="loading"
        :data="modelDataList2"
      >

        <el-table-column
          align="center"
          label="顺序号"
          prop="sortNum"/>
        <el-table-column
          align="center"
          label="阶段最大功率（单位：W）"
          prop="beginDuration">
          <template slot-scope="scope">
            {{ scope.row.beginDuration }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="服务费（元）"
          prop="serviceFeeShow">
        </el-table-column>
        <el-table-column
          align="center"
          label="电价（元/小时）"
          prop="electricityPrice">
          <template slot-scope="scope">
            {{ scope.row.electricityPriceShow }}
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-if="billingModel.billingModelStageType == 'T'"
        v-loading="loading"
        :data="modelDataList2"
        @selection-change="handleSelectionChange">

        <el-table-column
          align="center"
          label="顺序号"
          prop="sortNum"/>
        <el-table-column
          align="center"
          label="起始时间"
          prop="beginDuration">
          <template slot-scope="scope">
            {{ ChangeHourMinutestr(scope.row.beginDuration) }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="服务费"
          prop="serviceFeeShow">

        </el-table-column>
        <el-table-column
          align="center"
          label="电价"
          prop="electricityPrice">
          <template slot-scope="scope">
            {{ scope.row.electricityPriceShow }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMode">确 定</el-button>
        <el-button @click="cancelBind">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManager,
  getManager,
  getManagerDetail,
  delManager,
  addManager,
  updateManager,
  listDevice,
  getInfo,
  setManager,
  getBasisInfo,
  getQrcode, managerRestart,hotMapList
} from "@/api/business/manager";
import {listModel, getModel, updateModelBind, getModelByProtocolName} from '@/api/business/model'
import {ChangeHourMinutestr, ChangeStrToMinutes} from '@/utils/common'
import {getAllChargeStation} from '@/api/business/station'
import {listAgent} from '@/api/platform/agent'
import {listAllData} from "@/api/system/dict/data";
import {formatDate} from '@/utils/index'
import LineChart from '@/views/dashboard/LineChart'
import dynamicFormItem from '@/views/business/manager/dynamicFormItem.vue'
import QrItem from '@/views/business/manager/components/qrcode.vue'
import BinChart from '@/views/dashboard/Bin'
import HeatMap from "@/views/dashboard/HeatMap.vue";
import {listDeviceFaultRecord, delDeviceFaultRecord, getDeviceFaultRecordBin} from "@/api/business/deviceFaultRecord";

const newVisitis = {
  expectedData: [100, 120, 161, 134, 105, 160, 165],
  actualData: [120, 82, 91, 154, 162, 140, 145]
}
const statusList = [{value: 0, label: '离线'}, {value: 1, label: '在线'},{value: 2, label: '已升级'}]

const dictList = ['UR4','M8']
export default {
  name: "Manager",
  data() {
    return {
      active: null,
      // 二维码所需参数
      innerVisibleText: null,
      imageUrl: require("@/assets/logo/logo.png"),
      codeUrl: '',
      stationName: '',
      deviceName: '',
      chargePort: '',
      showLogo: false,
      decDeviceId: null,
      innerVisible: false,
      ChangeHourMinutestr,
      statusList,
      value: true,
      lineChartData: newVisitis,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充电桩管理表格数据
      managerList: [],
      stationList: [],
      dictList,
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      selectQueryParams: {
        pageNum: 1,
        pageSize: 100,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        decDeviceId: null,
        deviceId: null,
        deviceName: null,
        chargePortNumber: null,
        chargePortReportFre: null,
        communicationModuleValue: null,
        configStatus: null,
        deviceType: null,
        dtuSignalValue: null,
        heartbeatReportFre: null,
        hexCardNo: null,
        hexIccId: null,
        hexImei: null,
        iccId: null,
        imei: null,
        lastHeartbeatTime: null,
        leakageProtectionActionTime: null,
        masterControlVersion: null,
        maxChargeCurrents: null,
        maxChargePower: null,
        maxChargeVoltage: null,
        maxCurrentsOfLeakageProtection: null,
        registerTime: null,
        selfInspectionResults: null,
        signalVal: null,
        stationId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      infoForm: {},
      formInfo: {},
      openSetting: false,
      formDetail: {},
      activeName: '基础属性',
      openMode: false,
      modeDetail: {},
      modelList: [],
      selectManager: '',
      billingModel: {},
      modelDataList2: [],
      deviceVoMap: {},
      deviceSetUpInfoMap: [],
      webBillingModelShowVoMap: {},
      runTimeMap: [],
      chargeOrderCountMapList:[],
      faultCountMapList:[],
      heartCountMapList:[],
      billingModelStageType: '',
      chargePortVoList: [],
      imgUrl: null,
      deviceIdCode: '',

      deviceFaultRecordList: [],
      total2: 0,
      queryParams2: {
        pageNum: 1,
        pageSize: 10
      },
      deviceId: '',
      binData: [],
      binShow: false,
      hotMapList:{

      },
    };
  },
  components: {
    LineChart,
    dynamicFormItem,
    QrItem,
    BinChart,
    HeatMap
  },
  created() {
    this.getList();
    //this.getListDevice()
    this.getListStation()
    this.getListAgent()
  },
  methods: {
    handleManagerRestart(row) {
      this.$confirm('此操作将重启该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await managerRestart(row.deviceId)
        this.$message({
          type: res.data ? 'info' : 'warning',
          message: res.data ? '重启成功' : '重启失败'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    handleDeleteRecodes(row, index) {
      this.$confirm('此操作将删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        if (row.id) {
          let res = delDeviceFaultRecord(row.id)
          this.$modal.msgSuccess("删除成功");
          this.deviceFaultRecordList.splice(index, 1);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    openInnerVisible(index, port) {
      this.innerVisibleText = index
      this.innerVisible = !this.innerVisible
      this.getcode(this.deviceIdCode, port)
    },
    getcode(deviceId, port) {
      getQrcode(deviceId, port).then(res => {
        console.log(res)
        this.codeUrl = res.data.url
        this.stationName = res.data.stationName
        this.deviceName = res.data.deviceName
        this.chargePort = res.data.chargePort
        this.showLogo = res.data.showLogo
        this.decDeviceId = res.data.decDeviceId
      })
    },
    formatDate,
    submitMode() {
      if (!this.selectManager) {
        this.$modal.msgError("充电桩设备信息缺失");
        return false
      }
      this.modeDetail.deviceId
      let paramsObj = {
        deviceId: this.modeDetail.deviceId,
        billingModelId: this.selectManager
      }
      updateModelBind(paramsObj).then(res => {
        this.$modal.msgSuccess("修改成功");
        this.openMode = false;
        this.getList();
      })
    },
    handleClickTabs(e) {
      if (e.index == 4) {
        this.getList2()
      }
      if (e.index == 5) {
        this.binShow = true
        this.getBin()
      }
    },
    changeModes(e) {
      console.log(e)
      this.selectManager = e
      getModel(e).then(response => {
        this.billingModel = response.data.billingModel
        console.log(this.billingModel)
        this.modelDataList2 = response.data.billingModelStageList
      })
    },
    /** 设备设置列表 **/
    /*getListDevice() {
      this.loading = true;
      listDevice().then(response => {
        this.loading = false;
      });
    },*/
    async getListMode(protocolName) {
      try {
        let res = await getModelByProtocolName(protocolName)
        console.log(res)
        this.modelList = res.data
      }catch (e) {

      }
    },
    /** 查询代理商列表 **/
    async getListAgent() {
      let res = await listAgent(this.selectQueryParams)
      this.agentList = res.rows;
      console.log(res)
    },
    /** 查询场站列表 **/
    async getListStation() {
      let res = await getAllChargeStation()
      this.stationList = res.data;
      console.log(res)
    },
    /** 查询充电桩管理列表 */
    getList() {
      this.loading = true;
      listManager(this.queryParams).then(response => {
        this.managerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getList2() {
      listDeviceFaultRecord(this.queryParams2).then(res => {
        this.deviceFaultRecordList = res.rows
        this.total2 = res.total;
        this.loading = false;
      })
    },
    getBin() {
      getDeviceFaultRecordBin(this.deviceId).then(res => {
        this.binData = res.data
        this.binShow = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        cardBoardVersion: null,
        cardNo: null,
        chargePortNumber: null,
        chargePortReportFre: null,
        communicationModuleValue: null,
        configStatus: null,
        deviceType: null,
        dtuSignalValue: null,
        heartbeatReportFre: null,
        hexCardNo: null,
        hexIccId: null,
        hexImei: null,
        iccId: null,
        imei: null,
        lastHeartbeatTime: null,
        leakageProtectionActionTime: null,
        masterControlVersion: null,
        maxChargeCurrents: null,
        maxChargePower: null,
        maxChargeVoltage: null,
        maxCurrentsOfLeakageProtection: null,
        registerTime: null,
        selfInspectionResults: null,
        signalVal: null,
        stationId: null,
        status: null,
        map: null,
        center: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      /* this.reset();
       this.open = true;
       this.title = "添加充电桩管理";*/
      this.$modal.confirm('暂不支持手动新增充电桩信息!')
    },
    /** 计费模型弹窗 */
    async handleMode(row) {
      this.title = '计费模型'
      this.openMode = true
      this.modeDetail = row
      this.selectManager = this.modeDetail.billingModelId
      if (this.selectManager) {
        await getModel(this.selectManager).then(response => {
          this.billingModel = response.data.billingModel
          this.modelDataList2 = response.data.billingModelStageList
          this.getListMode(response.data.billingModel.protocolName)
        })
      }

    },
    /** 设置按钮操作 */
    handleSetting(row) {
      const deviceId = row.deviceId || this.ids
      getBasisInfo(deviceId).then(res => {
        if (res.data.length == 0) {
          this.$modal.msgError("充电桩设备信息缺失");
          return false
        }
        this.openSetting = true
        let a = []
        let obj = []
        res.data.forEach((item, index) => {
          a.push(item.attrModelCategory)
        })
        let aList = [...new Set(a)]
        aList.forEach(i => {
          let oo = res.data.filter((item, index) => {
            if (i === item.attrModelCategory) return item
          })
          //obj[i].push(oo)
          obj.push({
            label: i,
            list: oo
          })

        })
        this.infoForm = obj
        console.log(this.infoForm)
      })

    },
    /** 设置提交操作 */
    submitSetting() {
      let formatParamsTemp = []
      let formatParams = []
      Object.keys(this.infoForm).forEach((key) => {
        formatParamsTemp = [...formatParamsTemp, ...this.infoForm[key].list]
      })
      formatParamsTemp.forEach(item => {
        formatParams.push({
          deviceId: item.deviceId,
          id: item.id,
          settingValue: item.settingValue
        })
      })

      setManager(formatParams).then(response => {
        this.$modal.msgSuccess("设置成功");
        this.openSetting = false;
        this.getList();
      }).catch(() => {
        //this.$modal.msgError("设置失败");
      });
    },
    cancelSetting() {
      this.openSetting = false;
    },
    cancelBind() {
      this.openMode = false;
    },
    /** 设置切换类别 */
    tabSetting(tabsName) {
      //console.log(tabsName.label)
    },
    handleInput(val, index, key) {
      //console.log(val)
      //this.infoForm[index][key].settingValue = val
      //console.log('val',val,index,key)
      this.infoForm[index].list[key].settingValue = val
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getManager(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改充电桩管理";
      });
    },
    getKeyArr(arr) {
      let a = []
      let obj = []
      arr.forEach((item, index) => {
        a.push(item.attrModelCategory)
      })
      let aList = [...new Set(a)]
      aList.forEach(i => {
        let oo = arr.filter((item, index) => {
          if (i === item.attrModelCategory) return item
        })
        obj.push({
          label: i,
          list: oo
        })
      })
      return obj
    },
    async getHotMapList(deviceId){
      try {
        let res = await hotMapList(deviceId,new Date().getFullYear())
          this.chargeOrderCountMapList = res.data.chargeOrderCountMapList.map(obj => Object.entries(obj)[0])
          this.faultCountMapList = res.data.faultCountMapList.map(obj => Object.entries(obj)[0])
          this.heartCountMapList = res.data.heartCountMapList.map(obj => Object.entries(obj)[0])
      }catch (e) {

      }
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      console.log(row)
      this.getHotMapList(row.deviceId)
      this.activeName = '基础属性'
      let {latitude, longitude} = row
      this.openDetail = true;
      this.title = "充电桩详情";
      this.deviceId = row.deviceId
      this.queryParams2.deviceId = row.deviceId
      const deviceId = row.deviceId || this.ids
      this.deviceIdCode = row.deviceId || this.ids
      getManagerDetail(deviceId).then(response => {
        this.formDetail = response.data;
        this.deviceVoMap = this.formDetail.deviceVoMap['基础属性']
        this.deviceSetUpInfoMap = this.formDetail.deviceSetUpInfoMap['设备硬件']
        this.webBillingModelShowVoMap = this.formDetail.webBillingModelShowVoMap['计费模型']
        this.billingModelStageType = this.webBillingModelShowVoMap.billingModel.billingModelStageType
        this.runTimeMap = this.formDetail.runTimeMap['运行参数']
        // this.hotMapList = this.formDetail.hotMapList.map(obj => Object.entries(obj)[0])
        // const numbers = this.hotMapList.flat().filter(item => typeof item === 'number');
        // this.hotMax = numbers.reduce((p, c) => Math.max(p, c), -Infinity);
        this.deviceSetUpInfoMap = this.getKeyArr(this.deviceSetUpInfoMap)
        this.runTimeMap = this.getKeyArr(this.runTimeMap)
        this.chargePortVoList = this.formDetail.chargePortVoList
      });
      this.$nextTick(() => {
        this.initMap(latitude, longitude)
      });
    },
    /** initMap **/
    initMap(latitude, longitude) {
      //重复打开，初始化dom为空,处理重复地图问题
      document.getElementById("container").innerHTML = "";
      this.center = new TMap.LatLng(latitude, longitude)
      //初始化地图

      this.map = new TMap.Map(document.getElementById('container'), {
        center: this.center,//设置地图中心点坐标
        // zoom: 17.2,   //设置地图缩放级别
        // pitch: 43.5,  //设置俯仰角
        // rotation: 45    //设置地图旋转角度
      });

//设定marker点及其样式
      let markerLayer = new TMap.MultiMarker({
        map: this.map,  //指定地图容器
        //样式定义
        styles: {
          //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          "myStyle": new TMap.MarkerStyle({
            // "width": 25,  // 点标记样式宽度（像素）
            // "height": 35, // 点标记样式高度（像素）
            // "src": './images/R-C.png',  //图片路径
            //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
            // "anchor": { x: 16, y: 32 }
          })
        },
        geometries: [{
          "id": "1",   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
          "styleId": 'myStyle',  //指定样式id
          "position": this.center,  //点标记坐标位置
          "properties": {//自定义属性
            "title": "荆州万达广场",
            "imageUrl": './images/兔子1.gif',
          }
        }]
      });

      //监听点击事件添加marker
      this.map.on("click", (evt) => {
        console.log(evt)
        let {lat, lng} = evt.latLng
        markerLayer.setGeometries([])
        markerLayer.updateGeometries([
          {
            "styleId": "marker",
            "position": new TMap.LatLng(lat, lng),
          }
        ]);
      });
    },
    /** 切换按钮 **/
    handleChange(index, row) {
      this.$confirm('提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //this.value ? row.showState = true : row.showState = false
        this.value = !this.value
        this.$message({type: 'success', message: '修改成功!'})
      }).catch(() => {
        this.$message({type: 'info', showClose: true, message: '已取消修改！'})
      });
    },
    updateManager(row, key1, key2) {
      if (row[key2] === 0) {
        this.$modal.msgError('警告')
      }
      this.$confirm('是否确认此操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        row[key1] === 1 ? row[key1] = 0 : row[key1] = 1
        try {
          let res = await updateManager(row)
          this.$modal.msgSuccess(res.msg)
        } catch (e) {
          this.$modal.msgError(e)
        }
      }).catch(() => {
        this.$message.info('取消操作！')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateManager(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManager(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除充电桩管理编号为"' + deviceIds + '"的数据项？').then(function () {
        return delManager(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/manager/export', {
        ...this.queryParams
      }, `manager_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.items {
  width: 100%;
  height: 710px;

  display: flex;
  justify-content: space-between;

  .itemleft1 {
    width: 58%;
    height: 100%;
  }

  .itemleft2 {
    width: 40%;
    height: 100%;
  }
}

#container {
  border: 1px solid #5a5e66;
  padding: 5px;
}

::v-deep .el-switch.is-disabled {
  opacity: 1;
}

::v-deep .el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label {
  cursor: pointer !important;
}

.footer_all {
  display: flex;
  justify-content: space-between;
}
</style>
